import React, { useState } from 'react';
import {
  Form,
  Row,
  Col,
  Button,
  DatePicker,
  Select,
  Table,
  Input,
  Popover,
  Badge,
  message,
} from 'antd';
import moment from 'moment';
import { history } from 'umi';
import request from '@/http';
import { askForLeave } from '@/pages/login/service';
import { log } from 'util';
const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [expand, setExpand] = useState(true);
  const [form] = Form.useForm();
  const formItemLayout = {
    labelCol: {
      xs: { span: 7 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const getFields = () => {
    const count = expand ? 10 : 6;
    const children = [];
    children.push(
      <Col span={8}>
        <Form.Item name="date" label="申请提交日期:">
          <RangePicker showTime />
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="status" label="审批状态：">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            <Option value="审批中">审批中</Option>
            <Option value="审批不通过">审批不通过</Option>
            <Option value="审批通过">审批通过</Option>
          </Select>
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="leaveType" label="请假原因：">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            <Option value="病假">病假</Option>
            <Option value="事假">事假</Option>
            <Option value="其他">其他</Option>
          </Select>
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="theme" label="主题：">
          <Input placeholder="请输入..." />
        </Form.Item>
      </Col>,
    );
    return children;
  };

  const columns = [
    {
      title: '申请提交日期',
      dataIndex: 'submitTime',
      key: 'submitTime',
    },
    {
      title: '主题',
      dataIndex: 'theme',
      key: 'theme',
    },
    {
      title: '请假原因',
      dataIndex: 'leaveType',
      key: 'leaveType',
      render: (leaveType: any) => {
        if (leaveType == '0') {
          return <span>病假</span>;
        } else if (leaveType == '1') {
          return <span>事假</span>;
        } else {
          return <span>其他</span>;
        }
      },
    },
    {
      title: '原因说明',
      dataIndex: 'reason',
      key: 'reason',
    },
    {
      title: '请假开始时间',
      dataIndex: 'startLeaveTime',
      key: 'startLeaveTime',
    },
    {
      title: '请假结束时间',
      dataIndex: 'endLeaveTime',
      key: 'endLeaveTime',
    },
    {
      title: '审批状态',
      dataIndex: 'status',
      key: 'status',
      render: (age: any) => {
        if (age == '1') {
          return <Badge status="error" text="审批不通过" />;
        } else if (age == '2') {
          return <Badge status="success" text="审批通过" />;
        } else if (age == '0') {
          return <Badge status="processing" text="审批中" />;
        }
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any) => {
        if (text.status == '1') {
          const text1 = <span>不通过原因</span>;
          const [reason2, setReason2] = useState([]);
          const content = () => {
            request
              .get('/api/student/queryFailReasonByLeaId?leaveId=' + text.id)
              .then((result: any) => {
                setReason2(result.data);
              });
            return <p>{reason2}</p>;
          };
          return (
            <>
              <Button
                type="link"
                onClick={() => {
                  askForLeave.saveAskForLeaveId({
                    id: text.id,
                    status: text.status,
                    role: 1,
                    info: { ...text },
                    key: 1,
                  });
                  history.push('/global/askForLeave/particulars');
                }}
              >
                详情
              </Button>
              <Button
                type="link"
                onClick={() => {
                  askForLeave.saveAskForLeaveId({
                    id: text.id,
                    state: 1,
                  });
                  history.push('/global/askForLeave/dispose');
                }}
              >
                编辑
              </Button>
              <Popover
                placement="topLeft"
                title={text1}
                content={content}
                trigger="click"
              >
                <Button type="link">不通过原因</Button>
              </Popover>
            </>
          );
        } else {
          return (
            <Button
              type="link"
              onClick={() => {
                askForLeave.saveAskForLeaveId({
                  id: text.id,
                  status: text.status,
                  role: 1,
                  info: { ...text },
                  key: 1,
                });
                history.push('/global/askForLeave/particulars');
              }}
            >
              详情
            </Button>
          );
        }
      },
    },
  ];
  const [total2, setTotal2] = useState('');
  const [dataSource, setDataSource] = useState([]);
  const loadTable = async (
    queryParams: any,
    pageValue: any,
    pageSizeValue: any,
  ) => {
    try {
      setExpand(true);
      const result: any = await request.get('/api/student/queryStudentLeave', {
        params: {
          ...queryParams,
          current: pageValue,
          size: pageSizeValue,
        },
      });
      if (result.success) {
        const data = result.data.records.map((leave: any) => ({
          key: `leave_${leave.id}`,
          id: leave.id,
          endLeaveTime: leave.endLeaveTime,
          leaveType: leave.leaveType,
          reason: leave.reason,
          startLeaveTime: leave.startLeaveTime,
          status: leave.status,
          submitTime: leave.submitTime,
          theme: leave.theme,
        }));
        setExpand(false);
        setDataSource(data);
      }
      setTotal2(result.data.total);
    } catch (e) {
      message.error('错误');
    }
  };
  React.useEffect(() => {
    loadTable('', 1, 10).finally();
  }, []);

  const pagination = {
    total: parseInt(total2),
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['5', '10', '50', '100'],
  };
  // console.log(total2);

  const onFinish = (values: any) => {
    // console.log('Received values of form: ', values);
    let state = ''; //审批状态
    let leaveType = ''; //请假类型
    if (values.status == '审批中') {
      state = '0';
    } else if (values.status == '审批不通过') {
      state = '1';
    } else if (values.status == '审批通过') {
      state = '2';
    }

    if (values.leaveType == '病假') {
      leaveType = '0';
    } else if (values.leaveType == '事假') {
      leaveType = '1';
    } else if (values.leaveType == '其他') {
      leaveType = '2';
    }
    const data = {
      leaveType: leaveType,
      status: state,
      theme: values.theme,
      startLeaveTime: values.date
        ? values.date[0].format('yyyy-MM-DD HH:MM:SS')
        : '',
      endLeaveTime: values.date
        ? values.date[1].format('yyyy-MM-DD HH:MM:SS')
        : '',
    };
    loadTable(data, 1, 10).finally();
    console.log(data);
  };

  const pageOnChange = (page: any) => {
    const data = {
      leaveType: form.getFieldsValue().leaveType,
      status: form.getFieldsValue().state,
      theme: form.getFieldsValue().theme,
      startLeaveTime: form.getFieldsValue().date
        ? form.getFieldsValue().date[0].format('yyyy-MM-DD HH:MM:SS')
        : '',
      endLeaveTime: form.getFieldsValue().date
        ? form.getFieldsValue().date[1].format('yyyy-MM-DD HH:MM:SS')
        : '',
    };

    loadTable(data, page.current, page.pageSize).then();
  };

  return (
    <>
      <Form
        {...formItemLayout}
        form={form}
        name="advanced_search"
        className="ant-advanced-search-form"
        onFinish={onFinish}
      >
        <Row gutter={24}>{getFields()}</Row>
        <Row>
          <Col span={24} style={{ textAlign: 'left' }}>
            <Button
              type="primary"
              style={{ margin: '0 8px', width: '7%' }}
              onClick={() => {
                askForLeave.saveAskForLeaveId({
                  id: null,
                  state: 0,
                });
                history.push({
                  pathname: '/global/askForLeave/dispose',
                });
              }}
            >
              +新增请假
            </Button>
            <Button type="primary" style={{ width: '7%' }} htmlType="submit">
              查询
            </Button>
            <Button
              style={{ margin: '0 8px', width: '7%' }}
              onClick={() => {
                form.resetFields();
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
      <Table
        loading={expand}
        columns={columns}
        dataSource={dataSource}
        pagination={pagination}
        onChange={pageOnChange}
      />
    </>
  );
};
